package service

import (
	"QHMedLink/model"
	"time"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

// 1. 创建招聘信息（带事务）
func CreateRecruitment(db *gorm.DB, recruitment *model.Recruitment) error {
	return db.Transaction(func(tx *gorm.DB) error {
		return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(recruitment).Error
	})
}

// 2. 按城市+状态筛选（分页）
func GetRecruitmentsByCityStatus(db *gorm.DB, city string, status model.RecruitmentStatus, page, size int) ([]model.Recruitment, error) {
	var list []model.Recruitment
	offset := (page - 1) * size
	query := db.Where("city = ? AND status = ?", city, status)
	if err := query.Offset(offset).Limit(size).Order("publish_time DESC").Find(&list).Error; err != nil {
		return nil, err
	}
	return list, nil
}

// 3. 更新招聘状态（带条件校验）
func UpdateRecruitmentStatus(db *gorm.DB, id uint, newStatus model.RecruitmentStatus) error {
	return db.Model(&model.Recruitment{}).
		Where("info_id = ? AND status != ?", id, model.StatusClosed).
		Update("status", newStatus).Error
}

// 4. 复合条件查询（薪资+截止日期）
func GetRecruitmentsBySalaryAndDeadline(db *gorm.DB, minSalary, maxSalary string, deadline time.Time) ([]model.Recruitment, error) {
	var list []model.Recruitment
	query := db.Where("salary_range >= ? AND salary_range <= ?", minSalary, maxSalary)
	if !deadline.IsZero() {
		query = query.Where("deadline <= ?", deadline)
	}
	if err := query.Find(&list).Error; err != nil {
		return nil, err
	}
	return list, nil
}

// 5. 软删除（需扩展模型添加DeletedAt字段）
func SoftDeleteRecruitment(db *gorm.DB, id uint) error {
	return db.Model(&model.Recruitment{}).
		Where("info_id = ?", id).
		Update("is_deleted", true).Error
}
